package user.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import user.contstant.Constants;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * PassTemplate Token Upload
 */

@Slf4j
@Controller
public class TokenUploadController {

    /**redis客户端*/
    private final StringRedisTemplate redisTemplate;
    @Autowired
    public TokenUploadController(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/upload")
    public String upload(){
        return "upload";
    }

    //token上传
    @PostMapping("/token")
    public String tokenFileUpload(@RequestParam("merchantId") String merchantsId,
                                  @RequestParam("passTemplateId") String passTemplateId,
                                  @RequestParam("file") MultipartFile file,
                                  RedirectAttributes redirectAttributes){

        //进行判断
        if(passTemplateId == null || file.isEmpty()){
            redirectAttributes.addFlashAttribute("message",
                    "passTemplateId is null or file is empty");
            return "redirect:/uploadStatus";
        }

        //获取上传文件存储的目录
        File cur = new File(Constants.TOKEN_DIR + merchantsId);
        //不存在则创建
        if(! cur.exists()){
            log.info("create file:{}",cur.mkdir());
        }
        //写操作
        Path path = Paths.get(Constants.TOKEN_DIR,merchantsId,passTemplateId);
        try {
            Files.write(path,file.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
        //写入redis
        if(! writeTokenToRedis(path,passTemplateId)){
            redirectAttributes.addFlashAttribute("message","write token error");
        }
        else
            redirectAttributes.addFlashAttribute("message","success" + file.getOriginalFilename());

        return  "redirect:/uploadStatus";
    }
    @GetMapping("/uploadStatus")
    public String uploadStatus(){
        return "uploadStatus";
    }
    /**
     * 将token写入redis
     * @param path {@link Path}
     * @param key redis key
     * @return  true/false
     */
    private boolean writeTokenToRedis(Path path, String key){

        Set<String> tokens;
        //获取tokens
        try(Stream<String> stream = Files.lines(path)){
            tokens = stream.collect(Collectors.toSet());
        }catch (IOException e){
            e.printStackTrace();
            return false;
        }
        //判断是否为空
        if (! CollectionUtils.isEmpty(tokens)){
            //写入
            redisTemplate.executePipelined(
                    (RedisCallback<Object>) connection -> {
                        for (String token : tokens){
                            connection.sAdd(key.getBytes(),token.getBytes());
                        }
                        return null;
            });
            return true;
        }
        return false;
    }
}
